#-*- encoding=utf-8 -*-
from api import KuaiPanAPI
from http import randstr
from time import time
from cStringIO import StringIO
from zipfile import ZipFile
from os import path

class Test(object):
    
    def __init__(self, settings):
        self.username = settings['username']
        self.userpwd = settings['userpwd']
        server_time = KuaiPanAPI.open_time()
        difftime = int(server_time.get('Timestamp')) - int(time())
        self.kp = KuaiPanAPI(consumer_key=settings['consumer_key'], consumer_secret=settings['consumer_secret'], difftime=difftime, root=settings['root'])
    
    
    def test_oauth(self):
        print('Test OAuth, 3 steps:')
        
        resp = self.kp.open_request_token()
        print('1 / 3. open_request_token : %s' % resp)
        assert resp.get('oauth_token') is not None
        assert resp.get('oauth_token_secret') is not None
        
        resp = self.kp.authorize(self.username, self.userpwd)
        print('2 / 3. authorize : %s' % resp)
        assert resp is not None
        
        resp = self.kp.open_access_token(resp)
        print('3 / 3. open_access_token : %s' % resp)
        assert resp.get('oauth_token') is not None
        assert resp.get('oauth_token_secret') is not None
        assert resp.get('user_id') is not None
        
    
    def test_accoun_info(self):
        print('Test Get Account Info, 1 step')
        resp = self.kp.account_info()
        print('1 / 1, account_info : %s' % resp)
        assert resp.get('user_id') is not None
        assert resp.get('user_name') is not None
        assert resp.get('quota_total') is not None
        assert resp.get('quota_used') is not None
        assert resp.get('user_name') == self.username
 
    def test_fileops(self):
        print('Test File Operations, 10 steps')
        folder1 = u'/test目录1_%s' % randstr(10)
        folder2 = u'/test目录2_%s' % randstr(10)
        
        resp = self.kp.fileops_create_folder(folder1)
        print('1 / 22. fileops_create_folder : %s' % resp)
        assert resp.get('file_id') is not None
        
        resp = self.kp.fileops_upload_locate()
        upload_uri = resp.get('url')
        print('2 / 22. fileops_upload_locate : %s' % resp)
        assert upload_uri is not None
        if upload_uri == u'http://p5.dfs.kuaipan.cn:8080/cdlnode/':
            upload_uri = u'http://p4.dfs.kuaipan.cn/cdlnode/'
            print ('use upload_uri : %s' % upload_uri)
        
        f = open('test1.jpg', 'rb')
        f.seek(0, 2)
        size = f.tell()
        f.seek(0)
        filepath1 = folder1 + u'/测试.jpg'
        
        def uploadcb(total, sent):
            print ("File Upload : %s / %s" % (sent, total))
            
        resp = self.kp.fileops_upload_file(upload_uri, False, filepath1, f, size, callback=uploadcb)
        print('3 / 22. fileops_upload_file : %s' % resp)
        assert resp.get('file_id') is not None
        assert resp.get('rev') is not None
        assert resp.get('type') == 'file'
        assert int(resp.get('size')) == size
              
        resp = self.kp.fileops_download_file(filepath1, 50, 99)
        print('4 / 22. fileops_download_file : %s' % resp)
        f.seek(0)
        assert resp.read() == f.read(100)[50:]
        f.close()
        resp.close()
        
        resp = self.kp.metadata(folder1)    
        print('5 / 22. metadata (folder) : %s' % resp)
        assert resp.get('path') == folder1
        assert resp.get('root') == self.kp.root
        assert resp.get('file_id') is not None
        assert resp.get('type') == 'folder'
        assert resp.get('name') == path.basename(folder1)
        assert type(resp.get('files')) is list
        subfile = resp.get('files')[0]
        assert subfile.get('name') == path.basename(filepath1)
        assert subfile.get('size') == size
        
        
        resp = self.kp.metadata(filepath1)    
        print('6 / 22. metadata (file): %s' % resp)
        assert resp.get('path') == filepath1
        assert resp.get('root') == self.kp.root
        assert resp.get('file_id') is not None
        assert resp.get('type') == u'file'
        assert resp.get('name') == path.basename(filepath1)
        assert resp.get('size') == size
        
        resp = self.kp.fileops_copy(folder1, folder2)
        print('7 / 22. fileops_copy (folder) : %s' % resp)
        assert resp.get('file_id') is not None
       
        resp = self.kp.copy_ref(filepath1)
        copy_ref = resp.get('copy_ref')
        print('8 / 22. copy_ref (folder): %s' % resp)
        assert copy_ref is not None
        
        filepath2 = folder2 + u"/test2.jpg"
        resp = self.kp.fileops_copy(None, filepath2, copy_ref)
        print('9 / 22. fileops_copy (file by copy_ref) : %s' % resp)
        assert resp.get('file_id') is not None
        
        filepath3 = folder1 + u"/test2.jpg"
        resp = self.kp.fileops_move(filepath2, filepath3)
        print('10 / 22. fileops_move : %s' % resp)
        
        '''
        files = [filepath1, filepath2, filepath3]
        thumbnailinfo = {'width': '32', 'height': '32'}
        resp = self.kp.open_thumbnail(files, thumbnailinfo)
        print('11 / 22. open_thumbnail : %s' % resp)
        thumbnails = resp.get('thumbnails')
        assert type(thumbnails) is list
        assert len(thumbnails) == 3 
        return_pathes = [tn.get('files') for tn in thumbnails]
        for f in files:
            assert f in return_pathes
        '''
        
        resp = self.kp.open_fetch_file_timeline()
        print('12 / 22. open_fetch_file_timeline : %s' % resp)
        
        resp = self.kp.fileops_delete(filepath3, True)
        print('13 / 22. fileops_delete (file to recycle) : %s' % resp)
 
        resp = self.kp.fileops_delete(folder2, False)
        print('14 / 22. fileops_delete (folder not to recycle) : %s' % resp)
 
        resp = self.kp.fileops_thumbnail(64, 64, filepath1)
        print('15 / 22. fileops_thumbnail (64 x 64) : %s' % resp)
        thumbnail = resp.read()
        resp.close()
        assert len(thumbnail) > 32
        f = open('test1.thumbnail.jpg', 'wb')
        f.write(thumbnail)
        f.close()
        #'''
        resp = self.kp.open_thumbnail302(filepath1, 64, 64)
        print('16 / 22. open_thumbnail302 (64 x 64) : %s' % resp)
        thumbnail = resp.read()
        resp.close()
        assert len(thumbnail) > 32
        f = open('test1.thumbnail2.jpg', 'wb')
        f.write(thumbnail)
        f.close()
        #'''
        data = "Test Text!"
        size = len(data)
        f = StringIO(data)
   
        resp = self.kp.fileops_upload_file(upload_uri, True, filepath1, f, size)
        print('17 / 22. fileops_upload_file (overwrite) : %s' % resp)
        assert resp.get('file_id') is not None
        assert resp.get('rev') is not None
        assert resp.get('type') == 'file'
        assert int(resp.get('size')) == size
        
        resp = self.kp.history(filepath1)
        print('18 / 22. history : %s' % resp)
        assert resp.get('files') is not None
        version = resp.get('files')[0]
        assert version.get('file_id') is not None
        assert version.get('rev') is not None
        assert version.get('create_time') is not None
        
        filepath4 = folder1 + u"/test1.txt"
        resp = self.kp.fileops_move(filepath1, filepath4)
        print('19 / 22. fileops_move (rename): %s' % resp)
        
        resp = self.kp.fileops_document_view('txt', 'normal', False, filepath4)
        print('20 / 22. fileops_document_view : %s' % resp)
        docview = resp.read()
        assert docview.find(data)
        
        resp = self.kp.fileops_document_view('txt', 'normal', True, filepath4)
        print('21 / 22. fileops_document_view (zipped) : %s' % resp)
        docview = resp.read()
        zipped = ZipFile(StringIO(docview), 'r')
        infos = zipped.infolist()
        for info in infos:
            if info.filename.endswith('.html') or info.filename.endswith('.htm'):
                docview = zipped.read(info)
                assert docview.find(data)

        resp = self.kp.fileops_delete(folder1, True)
        print('22 / 22. fileops_delete (folder to recycle) : %s' % resp)
        
        
if __name__ == '__main__':
    import traceback
    try:

        settings = {'consumer_key' : 'Your consumer_key',
                   'consumer_secret' : 'Your consumer_secret',
                   'username' : 'Your username of test account',
                   'userpwd' : 'Your password',
                   'root' : 'kuaipan'}
                   
        test = Test(settings)
        test.test_oauth()
        test.test_accoun_info()
        test.test_fileops()
    except Exception, e:
        ex = traceback.format_exc()
        print(ex)
    
    
    